<?php

namespace app\admin\controller\system;

use app\admin\model\SystemGroup;
use app\admin\model\SystemGroupAdmin;
use app\admin\validate\SystemAdmin;
use app\common\controller\AdminBase;
use app\common\controller\PCBase;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

/**
 * 系统管理员控制器
 */
class Admin extends PCBase
{

    protected $model = null;

    protected $relationSearch = false;

    protected $prefix = "qu_";

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\SystemAdmin();
        $this->prefix = env('database.prefix');
    }

    /**
     * 列表
     */
    public function index()
    {
        $params           = $this->request->post();
        $nickname         = $params['nickname']??'';
        $username         = $params['username']??'';
        $role_id          = $params['role_id']??'';
        $status           = $params['status']??'';
        $employees_status = $params['employees_status']??'';
        $limit            = $params['limit']??10;
        $where            = [];

        if($username){
            $where[] = ['username','like',"%{$username}%"];
        }

        if($role_id){
            $where[] = ['group_ids','=',$role_id];
        }


        if($nickname){
            $where[] = ['nickname','like',"%{$nickname}%"];
        }

        if($status!==''){
            $where[] = ['status','=',$status];
        }

        if($employees_status!==''){
            $where[] = ['employees_status','=',$employees_status];
        }

        $order = ['id desc'];

        $list = $this->model
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $systemGroups = SystemGroup::where('status', 1)->column('id,name');
        $groupName = [];
        foreach ($systemGroups as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
        foreach ($list as $k => $v) {
            $group_arr = table("system_group_admin")
                ->alias('sga')
                ->field('sg.name')
                ->join("{$this->prefix}system_group sg", 'sga.group_id=sg.id')
                ->where('sga.admin_id', $v['id'])
                ->select();

            $group_text = "";
            $i = 0;
            foreach ($group_arr as $key => $val) {
                $group_text = $i == 0 ? $val['name'] : $group_text . "," . $val['name'];
                $i++;
            }
            $v['group_text'] = $group_text;
            unset($v['password']);
        }
        $data = [
            'total' => $list->total(),
            'list'  => $list->items(),
        ];
        return $this->jsonMessage(200, true, '操作成功!', $data);
    }


    /**
     * 添加
     */
    public function add()
    {
        $post = $this->request->post();
        Db::startTrans();
        try {
            //查看手机号或账户是否存在;
            $username   = $post['username']??'';
            $nickname   = $post['nickname']??'';
            $status     = $post['status']??'1';
            $phone      = $post['phone']??'';
            $password   = $post['password']??'123456';
            $group_ids  = $post['group_ids']??'';
            $head_image = $post['head_image']??'';
            $team       = $post['team']??'';
            $email      = $post['email']??'';
            $password   = md5($password);
            if(!$username){
                return $this->jsonMessage(201, false, '用户名称不能为空!', null);
            }
            if(!$phone){
                return $this->jsonMessage(201, false, '手机号不能为空!', null);
            }
            $group_id = '';
            if($group_ids){
                $group_id = current($group_ids);
            }
            //update 2024-08-02 数据写入 操作
            $insert_info = [
                'username'   =>$username,
                'nickname'   =>$nickname,
                'status'     =>$status,
                'phone'      =>$phone,
                'password'   =>$password,
                'head_image' =>$head_image,
                'team'       =>$team,
                'create_time'=>date("Y-m-d H:i:s", time()),
                'email'      =>$email,
                'group_ids'  =>$group_id,
            ];
            $this->model->insert($insert_info);
            $row = $this->model->where('username', $post['username'])->find();
            $groupadmin = [];
            foreach ($group_ids as $v) {
                $groupadmin[] = ['admin_id' => $row['id'], 'group_id' => $v];
            }
            $groupadminModel = new SystemGroupAdmin();
            $groupadminModel->saveAll($groupadmin);
            Db::commit();
            return $this->jsonMessage(200, true, '添加成功!', null);
        } catch (ValidateException $e) {
            Db::rollback();
            return $this->jsonMessage(201, false, $e->getError(), null);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }

    /**
     * 查找
     */
    public function find($id)
    {
        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }
        $groups = SystemGroupAdmin::where('admin_id', $row['id'])->column('group_id');
        $row['group_ids'] = $groups;
        return $this->jsonMessage(200, true, '获取成功!', $row);
    }

    /**
     * 修改
     *
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }

        $post = $this->request->post();
        Db::startTrans();
        try {
            validate(SystemAdmin::class)->scene('edit')->check($post);
            if (isset($post['password']) && $post['password'] != "") {
                $post['password'] = md5($post['password']);
            } else {
                unset($post['password']);
            }
            $row->save($post);
            $groupadminModel = new SystemGroupAdmin();
            $groupadminModel->where('admin_id', $row['id'])->delete();
            $group_ids = $post['group_ids'];
            $groupadmin = [];
            foreach ($group_ids as $v) {
                $groupadmin[] = ['admin_id' => $row['id'], 'group_id' => $v];
            }
            $groupadminModel->saveAll($groupadmin);
            Db::commit();
            return $this->jsonMessage(200, true, '操作成功!', null);
        } catch (ValidateException $e) {
            return error($e->getError());
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("--------:" . $e);
            return $this->jsonMessage(201, false, '保存失败', null);
        }
        return $this->jsonMessage(200, true, '操作成功!', $row);
    }

    /**
     * 数据删除
     */
    public function delete($id)
    {

        $ids = is_array($id) ? $id : explode(',', $id);
        $row = $this->model->where("id", "in", $ids)->select();
        if ($row->isEmpty()) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }
        if (in_array("1", $ids) || in_array(1, $ids)) {
            return $this->jsonMessage(201, false, '当前管理员不可以删除', null);
        }
        try {
            $save = $row->delete();
            SystemGroupAdmin::where('admin_id', 'in', $ids)->delete();
        } catch (\Exception $e) {
            return $this->jsonMessage(201, false, '删除失败', null);
        }
        if($save){
            return $this->jsonMessage(200, true, '删除成功!', null);
        }else{
            return $this->jsonMessage(201, false, '删除失败', null);
        }
    }


    /**
     * 状态启用、禁用
     */
    public function status($id, $status)
    {
        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在!', null);
        }
        $msg = $status == 0 ? "禁用" : "启用";
        try {
            $row->status = $status;
            $row->save();
            return $this->jsonMessage(200, true, '操作成功!', null);
        } catch (\Exception $e) {
            return $this->jsonMessage(201, false, '操作失败!', null);
        }
    }



}
